package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.controller.form.SaveRulesPowerForm;
import com.woniuxy.controller.info.Result;
import com.woniuxy.dao.MenusDao;
import com.woniuxy.model.Menus;
import com.woniuxy.model.RuleMenus;
import com.woniuxy.dao.RuleMenusDao;
import com.woniuxy.service.RuleMenusService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.util.exception.MenusException.MenusException;
import com.woniuxy.util.exception.accountException.RuleException;
import com.woniuxy.util.exception.code.MenusExceptionCode;
import com.woniuxy.util.exception.code.RuleExceptionCode;
import lombok.Data;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Kevin Martin
 * @since 2022-03-16
 */
@Service
public class RuleMenusServiceImpl extends ServiceImpl<RuleMenusDao, RuleMenus> implements RuleMenusService {
    @Resource
    private MenusDao menusDao;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> saveRulesPower(SaveRulesPowerForm saveRulesPowerForm) {
        final int formSize = saveRulesPowerForm.getMenusIds().size();
        if(formSize !=0){
            QueryWrapper<Menus> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("menus_id",saveRulesPowerForm.getMenusIds());
            List<Menus> list = menusDao.selectList(queryWrapper);
            if(list.size()!= formSize){
                throw new MenusException(MenusExceptionCode.Menus_NOTFIND_ERROR);
            }
        }
        QueryWrapper<RuleMenus> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rule_id",saveRulesPowerForm.getRuleId());
        boolean remove = remove(queryWrapper);
        if(formSize==0) return Result.getInstance().setMsg("授权成功");
        List<RuleMenus> ruleMenus = new ArrayList<>();
        for (Integer menusId : saveRulesPowerForm.getMenusIds()) {
            RuleMenus ruleMenus1 = new RuleMenus();
            ruleMenus1.setMenusId(menusId);
            ruleMenus1.setRuleId(saveRulesPowerForm.getRuleId());
            ruleMenus.add(ruleMenus1);
        }
        boolean b = saveBatch(ruleMenus);
        return Result.getInstance().setMsg("授权成功");
    }
}
